from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import func, and_, or_
from typing import List, Optional, Dict, Any
from datetime import datetime, timedelta
import json

from app.core.database import get_db
from app.core.security import get_current_active_user
from app.models.user import User
from app.models.analytics import UserBehavior, PageView, UserSession
from app.schemas.analytics import (
    UserBehavior as UserBehaviorSchema,
    PageView as PageViewSchema,
    UserSession as UserSessionSchema,
    UserBehaviorCreate,
    PageViewCreate,
    AnalyticsStats,
    UserActivityStats
)

router = APIRouter()

@router.post("/track/behavior", summary="记录用户行为")
async def track_user_behavior(
    behavior_data: UserBehaviorCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    记录用户行为数据
    """
    # 创建行为记录
    behavior = UserBehavior(
        user_id=current_user.id,
        action=behavior_data.action,
        target=behavior_data.target,
        target_id=behavior_data.target_id,
        metadata=behavior_data.metadata,
        ip_address=behavior_data.ip_address,
        user_agent=behavior_data.user_agent,
        session_id=behavior_data.session_id
    )
    
    db.add(behavior)
    db.commit()
    db.refresh(behavior)
    
    return {"message": "用户行为记录成功", "behavior_id": behavior.id}

@router.post("/track/pageview", summary="记录页面访问")
async def track_page_view(
    pageview_data: PageViewCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    记录页面访问数据
    """
    # 创建页面访问记录
    pageview = PageView(
        user_id=current_user.id,
        page_url=pageview_data.page_url,
        page_title=pageview_data.page_title,
        referrer=pageview_data.referrer,
        duration=pageview_data.duration,
        metadata=pageview_data.metadata,
        ip_address=pageview_data.ip_address,
        user_agent=pageview_data.user_agent,
        session_id=pageview_data.session_id
    )
    
    db.add(pageview)
    db.commit()
    db.refresh(pageview)
    
    return {"message": "页面访问记录成功", "pageview_id": pageview.id}

@router.get("/behaviors", response_model=List[UserBehaviorSchema], summary="获取用户行为列表")
async def get_user_behaviors(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(50, ge=1, le=200, description="返回记录数"),
    action: Optional[str] = Query(None, description="行为类型"),
    target: Optional[str] = Query(None, description="目标对象"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户行为数据列表
    """
    # 检查权限
    if not current_user.has_permission("analytics:read") and not current_user.is_superuser:
        # 普通用户只能查看自己的行为数据
        query = db.query(UserBehavior).filter(UserBehavior.user_id == current_user.id)
    else:
        # 管理员可以查看所有用户的行为数据
        query = db.query(UserBehavior)
    
    # 应用过滤条件
    if action:
        query = query.filter(UserBehavior.action == action)
    if target:
        query = query.filter(UserBehavior.target == target)
    if start_date:
        query = query.filter(UserBehavior.created_at >= start_date)
    if end_date:
        query = query.filter(UserBehavior.created_at <= end_date)
    
    behaviors = query.order_by(UserBehavior.created_at.desc()).offset(skip).limit(limit).all()
    
    return [UserBehaviorSchema.from_orm(behavior) for behavior in behaviors]

@router.get("/pageviews", response_model=List[PageViewSchema], summary="获取页面访问列表")
async def get_page_views(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(50, ge=1, le=200, description="返回记录数"),
    page_url: Optional[str] = Query(None, description="页面URL"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取页面访问数据列表
    """
    # 检查权限
    if not current_user.has_permission("analytics:read") and not current_user.is_superuser:
        query = db.query(PageView).filter(PageView.user_id == current_user.id)
    else:
        query = db.query(PageView)
    
    # 应用过滤条件
    if page_url:
        query = query.filter(PageView.page_url.like(f"%{page_url}%"))
    if start_date:
        query = query.filter(PageView.created_at >= start_date)
    if end_date:
        query = query.filter(PageView.created_at <= end_date)
    
    pageviews = query.order_by(PageView.created_at.desc()).offset(skip).limit(limit).all()
    
    return [PageViewSchema.from_orm(pageview) for pageview in pageviews]

@router.get("/stats/overview", response_model=AnalyticsStats, summary="获取分析概览")
async def get_analytics_overview(
    days: int = Query(30, ge=1, le=365, description="统计天数"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户行为分析概览统计
    """
    # 检查权限
    if not current_user.has_permission("analytics:read") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看分析数据"
        )
    
    # 计算时间范围
    end_date = datetime.utcnow()
    start_date = end_date - timedelta(days=days)
    
    # 总用户数
    total_users = db.query(User).count()
    
    # 活跃用户数（在指定时间内有行为记录的用户）
    active_users = db.query(UserBehavior.user_id).filter(
        UserBehavior.created_at >= start_date
    ).distinct().count()
    
    # 总页面访问量
    total_pageviews = db.query(PageView).filter(
        PageView.created_at >= start_date
    ).count()
    
    # 总用户行为数
    total_behaviors = db.query(UserBehavior).filter(
        UserBehavior.created_at >= start_date
    ).count()
    
    # 平均会话时长
    avg_session_duration = db.query(func.avg(UserSession.duration)).filter(
        UserSession.created_at >= start_date
    ).scalar() or 0
    
    # 跳出率（只访问一个页面的会话比例）
    single_page_sessions = db.query(UserSession).filter(
        UserSession.created_at >= start_date,
        UserSession.page_count == 1
    ).count()
    
    total_sessions = db.query(UserSession).filter(
        UserSession.created_at >= start_date
    ).count()
    
    bounce_rate = (single_page_sessions / total_sessions * 100) if total_sessions > 0 else 0
    
    return AnalyticsStats(
        total_users=total_users,
        active_users=active_users,
        total_pageviews=total_pageviews,
        total_behaviors=total_behaviors,
        avg_session_duration=round(avg_session_duration, 2),
        bounce_rate=round(bounce_rate, 2)
    )

@router.get("/stats/user-activity", summary="获取用户活动统计")
async def get_user_activity_stats(
    days: int = Query(7, ge=1, le=90, description="统计天数"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户活动趋势统计
    """
    # 检查权限
    if not current_user.has_permission("analytics:read") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看分析数据"
        )
    
    # 计算时间范围
    end_date = datetime.utcnow().date()
    start_date = end_date - timedelta(days=days-1)
    
    # 按日期统计用户活动
    daily_stats = []
    current_date = start_date
    
    while current_date <= end_date:
        next_date = current_date + timedelta(days=1)
        
        # 当日活跃用户数
        daily_active_users = db.query(UserBehavior.user_id).filter(
            and_(
                UserBehavior.created_at >= datetime.combine(current_date, datetime.min.time()),
                UserBehavior.created_at < datetime.combine(next_date, datetime.min.time())
            )
        ).distinct().count()
        
        # 当日页面访问量
        daily_pageviews = db.query(PageView).filter(
            and_(
                PageView.created_at >= datetime.combine(current_date, datetime.min.time()),
                PageView.created_at < datetime.combine(next_date, datetime.min.time())
            )
        ).count()
        
        # 当日用户行为数
        daily_behaviors = db.query(UserBehavior).filter(
            and_(
                UserBehavior.created_at >= datetime.combine(current_date, datetime.min.time()),
                UserBehavior.created_at < datetime.combine(next_date, datetime.min.time())
            )
        ).count()
        
        daily_stats.append({
            "date": current_date.isoformat(),
            "active_users": daily_active_users,
            "pageviews": daily_pageviews,
            "behaviors": daily_behaviors
        })
        
        current_date = next_date
    
    return {"daily_stats": daily_stats}

@router.get("/stats/popular-pages", summary="获取热门页面统计")
async def get_popular_pages(
    days: int = Query(30, ge=1, le=365, description="统计天数"),
    limit: int = Query(10, ge=1, le=50, description="返回数量"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取热门页面访问统计
    """
    # 检查权限
    if not current_user.has_permission("analytics:read") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看分析数据"
        )
    
    # 计算时间范围
    start_date = datetime.utcnow() - timedelta(days=days)
    
    # 统计页面访问量
    popular_pages = db.query(
        PageView.page_url,
        PageView.page_title,
        func.count(PageView.id).label('visit_count'),
        func.count(func.distinct(PageView.user_id)).label('unique_visitors'),
        func.avg(PageView.duration).label('avg_duration')
    ).filter(
        PageView.created_at >= start_date
    ).group_by(
        PageView.page_url, PageView.page_title
    ).order_by(
        func.count(PageView.id).desc()
    ).limit(limit).all()
    
    return {
        "popular_pages": [
            {
                "page_url": page.page_url,
                "page_title": page.page_title,
                "visit_count": page.visit_count,
                "unique_visitors": page.unique_visitors,
                "avg_duration": round(page.avg_duration or 0, 2)
            }
            for page in popular_pages
        ]
    }

@router.get("/stats/user-behavior-types", summary="获取用户行为类型统计")
async def get_behavior_types_stats(
    days: int = Query(30, ge=1, le=365, description="统计天数"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户行为类型分布统计
    """
    # 检查权限
    if not current_user.has_permission("analytics:read") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看分析数据"
        )
    
    # 计算时间范围
    start_date = datetime.utcnow() - timedelta(days=days)
    
    # 统计行为类型分布
    behavior_stats = db.query(
        UserBehavior.action,
        func.count(UserBehavior.id).label('count'),
        func.count(func.distinct(UserBehavior.user_id)).label('unique_users')
    ).filter(
        UserBehavior.created_at >= start_date
    ).group_by(
        UserBehavior.action
    ).order_by(
        func.count(UserBehavior.id).desc()
    ).all()
    
    return {
        "behavior_types": [
            {
                "action": behavior.action,
                "count": behavior.count,
                "unique_users": behavior.unique_users
            }
            for behavior in behavior_stats
        ]
    }

@router.get("/stats/user-retention", summary="获取用户留存统计")
async def get_user_retention_stats(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取用户留存率统计
    """
    # 检查权限
    if not current_user.has_permission("analytics:read") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看分析数据"
        )
    
    # 计算不同时期的留存率
    today = datetime.utcnow().date()
    
    retention_stats = []
    
    # 计算1天、7天、30天留存率
    for days in [1, 7, 30]:
        cohort_date = today - timedelta(days=days)
        
        # 获取该日期注册的用户
        cohort_users = db.query(User.id).filter(
            func.date(User.created_at) == cohort_date
        ).subquery()
        
        # 计算这些用户在今天是否还活跃
        retained_users = db.query(UserBehavior.user_id).filter(
            and_(
                UserBehavior.user_id.in_(cohort_users),
                func.date(UserBehavior.created_at) == today
            )
        ).distinct().count()
        
        total_cohort_users = db.query(cohort_users).count()
        
        retention_rate = (retained_users / total_cohort_users * 100) if total_cohort_users > 0 else 0
        
        retention_stats.append({
            "period": f"{days}天留存",
            "cohort_date": cohort_date.isoformat(),
            "total_users": total_cohort_users,
            "retained_users": retained_users,
            "retention_rate": round(retention_rate, 2)
        })
    
    return {"retention_stats": retention_stats}

@router.get("/stats/realtime", summary="获取实时统计")
async def get_realtime_stats(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    获取实时用户活动统计
    """
    # 检查权限
    if not current_user.has_permission("analytics:read") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看分析数据"
        )
    
    # 计算最近1小时的数据
    one_hour_ago = datetime.utcnow() - timedelta(hours=1)
    
    # 在线用户数（最近5分钟有活动的用户）
    five_minutes_ago = datetime.utcnow() - timedelta(minutes=5)
    online_users = db.query(UserBehavior.user_id).filter(
        UserBehavior.created_at >= five_minutes_ago
    ).distinct().count()
    
    # 最近1小时的页面访问量
    recent_pageviews = db.query(PageView).filter(
        PageView.created_at >= one_hour_ago
    ).count()
    
    # 最近1小时的用户行为数
    recent_behaviors = db.query(UserBehavior).filter(
        UserBehavior.created_at >= one_hour_ago
    ).count()
    
    # 最近访问的页面
    recent_pages = db.query(
        PageView.page_url,
        PageView.page_title,
        func.count(PageView.id).label('count')
    ).filter(
        PageView.created_at >= one_hour_ago
    ).group_by(
        PageView.page_url, PageView.page_title
    ).order_by(
        func.count(PageView.id).desc()
    ).limit(5).all()
    
    return {
        "online_users": online_users,
        "recent_pageviews": recent_pageviews,
        "recent_behaviors": recent_behaviors,
        "recent_pages": [
            {
                "page_url": page.page_url,
                "page_title": page.page_title,
                "count": page.count
            }
            for page in recent_pages
        ]
    }

@router.delete("/data/cleanup", summary="清理历史数据")
async def cleanup_analytics_data(
    days: int = Query(90, ge=30, le=365, description="保留天数"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    清理指定天数之前的分析数据
    """
    # 检查权限
    if not current_user.has_permission("analytics:admin") and not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限执行数据清理"
        )
    
    # 计算清理时间点
    cleanup_date = datetime.utcnow() - timedelta(days=days)
    
    # 清理用户行为数据
    deleted_behaviors = db.query(UserBehavior).filter(
        UserBehavior.created_at < cleanup_date
    ).delete()
    
    # 清理页面访问数据
    deleted_pageviews = db.query(PageView).filter(
        PageView.created_at < cleanup_date
    ).delete()
    
    # 清理用户会话数据
    deleted_sessions = db.query(UserSession).filter(
        UserSession.created_at < cleanup_date
    ).delete()
    
    db.commit()
    
    return {
        "message": "数据清理完成",
        "cleanup_date": cleanup_date.isoformat(),
        "deleted_behaviors": deleted_behaviors,
        "deleted_pageviews": deleted_pageviews,
        "deleted_sessions": deleted_sessions
    }